package org.example.controller;

import com.sun.net.httpserver.HttpExchange;
import org.example.service.BettingService;

import java.io.IOException;

public class StakeController extends BaseController {
    private final BettingService bettingService;
    private HttpExchange currentExchange;

    public StakeController(BettingService bettingService) {
        this.bettingService = bettingService;
    }

    @Override
    public String handleRequest() {

        try {
            Integer betOfferId = getIntPathParam("betOfferId");
            String sessionKey = getQueryParam("sessionkey");
            Integer stake = readIntRequestBody();

            if (betOfferId == null || sessionKey == null || stake == null) {
                return "ERROR:400:Missing or invalid required parameters";
            }

            boolean success = bettingService.placeStake(betOfferId, sessionKey, stake);

            if (success) {
                return "SUCCESS:200:"; // 空响应
            } else {
                return "ERROR:401:Invalid session";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "ERROR:500:Internal Server Error";
        }
    }

    /**
     * 设置当前的HttpExchange（由路由器在请求时设置）
     */
    public void setCurrentExchange(HttpExchange exchange) {
        this.currentExchange = exchange;
    }

    private String getQueryParam(String paramName) {
        if (currentExchange == null) return null;

        String query = currentExchange.getRequestURI().getQuery();
        if (query == null) return null;

        String[] params = query.split("&");
        for (String param : params) {
            if (param.startsWith(paramName + "=")) {
                return param.substring(paramName.length() + 1);
            }
        }
        return null;
    }

    private Integer readIntRequestBody() throws IOException {
        if (currentExchange == null) return null;

        String body = new String(currentExchange.getRequestBody().readAllBytes());
        if (body == null || body.trim().isEmpty()) return null;

        try {
            return Integer.parseInt(body.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
}